import 'dart:convert';
import 'dart:ui';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_easyrefresh/material_footer.dart';
import 'package:flutter_easyrefresh/material_header.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:gzx_dropdown_menu/gzx_dropdown_menu.dart';
import '../../http/Api.dart';
import '../../http/HttpUtil.dart';
import '../../util/SignUtil.dart';
import '../../base/Constant.dart';
import '../../entity/goods_list_entity.dart';
import '../goods/GoodsDetail.dart';
import 'package:cached_network_image/cached_network_image.dart';

class ShopGoodsListNoCatePage extends StatefulWidget {
  String cat_id;
  String name;
  ShopGoodsListNoCatePage({Key key, @required this.cat_id, @required this.name})
      : super(key: key);

  _ShopGoodsListNoCatePageState createState() => _ShopGoodsListNoCatePageState();
}

class _ShopGoodsListNoCatePageState extends State<ShopGoodsListNoCatePage> {
  List<GoodsModelData> homeListData = new List();
  // List catesData = new List();
  String cat_id = '';
  GZXDropdownMenuController _dropdownMenuController =
      GZXDropdownMenuController();
  List<String> sortList = ['综合', "价格", "销量"];
  var _scaffoldKey = new GlobalKey<ScaffoldState>();
  GlobalKey _stackKey = GlobalKey();
  EasyRefreshController _controller = new EasyRefreshController();
  final _searchController = TextEditingController();
  int page = 1;
  int currentShow = 1; //0 正常 1 网格
  String sort = 'total_sales_des';
  @override
  Widget build(BuildContext context) {
    ScreenUtil.instance = ScreenUtil(width: 750, height: 1334)..init(context);

    return Container(
      child: new Scaffold(
          appBar: new AppBar(
            title: Text(widget.name,
                style: TextStyle(
                    fontSize: ScreenUtil.getInstance().setSp(BIG_FONT_SIZE),
                    color: Colors.black)),
            backgroundColor: Colors.white,
            brightness: Brightness.light,
            centerTitle: true,
            iconTheme: new IconThemeData(color: Colors.black),
            elevation: 0.5,
          ),
          body: new Stack(
            key: _stackKey,
            children: <Widget>[
              new Column(
                children: <Widget>[
                  Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      Expanded(
                        flex: 2,
                        child: Container(
                          color: white,
                          padding: EdgeInsets.fromLTRB(0,
                              ScreenUtil.getInstance().setHeight(DP_8), 0, 0),
                          height: ScreenUtil.getInstance().setHeight(DP_60),
                          child: GZXDropDownHeader(
                            items: [
                              GZXDropDownHeaderItem(sortList[0]),
                              GZXDropDownHeaderItem(sortList[1]),
                              GZXDropDownHeaderItem(sortList[2]),
                            ],
                            stackKey: _stackKey,
                            controller: _dropdownMenuController,
                            onItemTap: (index) {},
                            height: ScreenUtil.getInstance().setHeight(DP_60),
                            color: white,
                            borderWidth: 1,
                            borderColor: white,
                            dividerColor: white,
                            style: TextStyle(
                                color: black_99,
                                fontSize: ScreenUtil.getInstance()
                                    .setSp(SMALL_FONT_SIZE)),
                            dropDownStyle: TextStyle(
                              fontSize: ScreenUtil.getInstance()
                                  .setSp(SMALL_FONT_SIZE),
                              color: mainColor,
                            ),
                            iconSize: ScreenUtil.getInstance().setHeight(DP_40),
                            iconColor: black_99,
                            iconDropDownColor: mainColor,
                          ),
                        ),
                      ),
                      Container(
                        height: ScreenUtil.getInstance().setHeight(DP_60),
                        color: white,
                        child: IconButton(
                          onPressed: () {
                            setState(() {
                              currentShow =
                                  (currentShow == 0 ? currentShow = 1 : 0);
                            });
                          },
                          icon: Image.asset(currentShow == 1
                              ? 'images/icon_list_vertical.png'
                              : 'images/icon_list_transverse.png'),
                        ),
                      ),
                    ],
                  ),
                  new Container(
                    height: MediaQuery.of(context).size.height -
                        kToolbarHeight -
                        ScreenUtil.getInstance().setHeight(DP_60) -
                        MediaQueryData.fromWindow(window).padding.top,
                    color: f0Color,
                    padding: EdgeInsets.all(ScreenUtil.getInstance().setHeight(10)),
                    child: new EasyRefresh(
                      controller: _controller,
                      header: MaterialHeader(),
                      footer: MaterialFooter(),
                      enableControlFinishLoad: true,
                      enableControlFinishRefresh: true,
                      child:
                          CustomScrollView(shrinkWrap: true, slivers: <Widget>[
                        // SliverGrid(
                        //   gridDelegate:
                        //       SliverGridDelegateWithMaxCrossAxisExtent(
                        //     maxCrossAxisExtent: kScreenWidth / 5,
                        //     mainAxisSpacing: kMargin10,
                        //     crossAxisSpacing: kMargin5,
                        //     childAspectRatio: 0.9, //子控件宽高比
                        //   ),
                        //   delegate: SliverChildBuilderDelegate(
                        //     (BuildContext context, int index) {
                        //       return catesData.length > 0
                        //           ? _item(context, index)
                        //           : Container();
                        //     },
                        //     childCount: catesData.length,
                        //   ),
                        // ),
                        currentShow == 0
                            ? SliverList(
                                delegate: SliverChildBuilderDelegate(
                                  (context, index) {
                                    if (homeListData.length > 0) {
                                      return _renderRow(context, index);
                                    } else {
                                      return Visibility(
                                        visible: true,
                                        child: Container(width: 0, height: 0),
                                      );
                                    }
                                  },
                                  childCount: homeListData.length,
                                ),
                              )
                            : SliverGrid(
                                gridDelegate:
                                    SliverGridDelegateWithMaxCrossAxisExtent(
                                  maxCrossAxisExtent: ScreenUtil.getInstance().setWidth(750) / 2,
                                  mainAxisSpacing: ScreenUtil.getInstance().setHeight(10),
                                  crossAxisSpacing: ScreenUtil.getInstance().setHeight(10),
                                  childAspectRatio: 0.62, //子控件宽高比
                                ),
                                delegate: SliverChildBuilderDelegate(
                                  (BuildContext context, int index) {
                                    return homeListData.length > 0
                                        ? getItemContainer(context, index)
                                        : Container();
                                  },
                                  childCount: homeListData.length,
                                ),
                              ),
                        // currentShow == 0
                        //   ? ListView.separated(
                        //       itemBuilder: _renderRow,
                        //       separatorBuilder:
                        //           (BuildContext context, int index) {
                        //         return Container(
                        //           color: divideColor,
                        //           height: 1,
                        //         );
                        //       },
                        //       itemCount: homeListData == null
                        //           ? 0
                        //           : homeListData.length)
                        //   : GridView.builder(
                        //       shrinkWrap: true,
                        //       gridDelegate:
                        //           SliverGridDelegateWithFixedCrossAxisCount(
                        //               crossAxisCount: 2,
                        //               mainAxisSpacing: 10.0,
                        //               crossAxisSpacing: 10.0,
                        //               childAspectRatio: 0.62),
                        //       itemBuilder: (context, index) {
                        //         return getItemContainer(context, index);
                        //       },
                        //       itemCount: homeListData == null
                        //           ? 0
                        //           : homeListData.length,
                        //     ),
                      ]),
                      onRefresh: () async {
                        page = 1;
                        loadList();
                      },
                      onLoad: () async {
                        page++;
                        loadList();
                      },
                    ),
                  ),
                ],
              ),
              GZXDropDownMenu(
                controller: _dropdownMenuController,
                animationMilliseconds: 0,
                menus: [
                  GZXDropdownMenuBuilder(
                      dropDownHeight:
                          ScreenUtil.getInstance().setHeight(DP_60) * 2 + 2,
                      dropDownWidget: new Column(
                        children: <Widget>[
                          Divider(
                            height: 1,
                            color: grey,
                          ),
                          new GestureDetector(
                            onTap: () {
                              setState(() {
                                sortList = ['综合', "价格", "销量"];
                                sortList[0] = "";
                                _dropdownMenuController.hide();
                                sort = '13';
                                loadList();
                              });
                            },
                            child: Container(
                              width: double.infinity,
                              height: ScreenUtil.getInstance().setHeight(DP_80),
                              padding: EdgeInsets.all(10),
                              child: Text(''),
                            ),
                          ),
                          Divider(
                            height: 1,
                            color: grey,
                          ),
                          new GestureDetector(
                            onTap: () {
                              setState(() {
                                sortList = ['综合', "价格", "销量"];
                                sortList[0] = "";
                                _dropdownMenuController.hide();
                                sort = '13';
                                loadList();
                              });
                            },
                            child: Container(
                              width: double.infinity,
                              height: ScreenUtil.getInstance().setHeight(DP_80),
                              padding: EdgeInsets.all(10),
                              child: Text(''),
                            ),
                          ),
                        ],
                      )),
                  GZXDropdownMenuBuilder(
                      dropDownHeight:
                          ScreenUtil.getInstance().setHeight(DP_80) * 2 + 2,
                      dropDownWidget: new Column(
                        children: <Widget>[
                          Divider(
                            height: 1,
                            color: grey,
                          ),
                          new GestureDetector(
                            onTap: () {
                              setState(() {
                                sortList = ['综合', "价格", "销量"];
                                sortList[1] = "价格升序";
                                _dropdownMenuController.hide();
                                sort = '2';
                                loadList();
                              });
                            },
                            child: Container(
                              width: double.infinity,
                              height: ScreenUtil.getInstance().setHeight(DP_80),
                              padding: EdgeInsets.all(10),
                              child: Text('价格升序'),
                            ),
                          ),
                          Divider(
                            height: 1,
                            color: grey,
                          ),
                          new GestureDetector(
                            onTap: () {
                              setState(() {
                                sortList = ['综合', "价格", "销量"];
                                sortList[1] = "价格降序";
                                _dropdownMenuController.hide();
                                sort = '1';
                                loadList();
                              });
                            },
                            child: Container(
                              width: double.infinity,
                              height: ScreenUtil.getInstance().setHeight(DP_80),
                              padding: EdgeInsets.all(10),
                              child: Text('价格降序'),
                            ),
                          ),
                        ],
                      )),
                  GZXDropdownMenuBuilder(
                      dropDownHeight:
                          ScreenUtil.getInstance().setHeight(DP_80) * 2 + 2,
                      dropDownWidget: new Column(
                        children: <Widget>[
                          Divider(
                            height: 1,
                            color: grey,
                          ),
                          new GestureDetector(
                            onTap: () {
                              setState(() {
                                sortList = ['综合', "价格", "销量"];
                                sortList[2] = "销量升序";
                                _dropdownMenuController.hide();
                                sort = '12';
                                loadList();
                              });
                            },
                            child: Container(
                              width: double.infinity,
                              height: ScreenUtil.getInstance().setHeight(DP_80),
                              padding: EdgeInsets.all(10),
                              child: Text('销量升序'),
                            ),
                          ),
                          Divider(
                            height: 1,
                            color: grey,
                          ),
                          new GestureDetector(
                            onTap: () {
                              setState(() {
                                sortList = ['综合', "价格", "销量"];
                                sortList[2] = "销量降序";
                                _dropdownMenuController.hide();
                                sort = '11';
                                loadList();
                              });
                            },
                            child: Container(
                              width: double.infinity,
                              height: ScreenUtil.getInstance().setHeight(DP_80),
                              padding: EdgeInsets.all(10),
                              child: Text('销量降序'),
                            ),
                          ),
                        ],
                      )),
                ],
              ),
            ],
          )),
    );
  }

  // Widget _item(BuildContext context, int index) {
  //   return GestureDetector(
  //     child: new Column(
  //       children: <Widget>[
  //         (catesData[index]['img'] == '' || catesData[index]['img'] == null)
  //             ? Image.asset('images/logo.png',
  //                 width: ScreenUtil.getInstance().setWidth(DP_90),
  //                 height: ScreenUtil.getInstance().setWidth(DP_90))
  //             : Image.network(
  //                 Api.BaseUrl + 'public/upload/' + catesData[index]['img'],
  //                 width: ScreenUtil.getInstance().setWidth(DP_90),
  //                 height: ScreenUtil.getInstance().setWidth(DP_90),
  //               ),
  //         Padding(
  //           padding: EdgeInsets.all(5),
  //           child: Text(
  //             catesData[index]['cat_name'],
  //             style: TextStyle(
  //                 fontSize: ScreenUtil.getInstance().setSp(MINI_FONT_SIZE),
  //                 color: Color.fromARGB(255, 66, 66, 66)),
  //           ),
  //         )
  //       ],
  //     ),
  //     onTap: () {
  //       setState(() {
  //         page = 1;
  //         cat_id = catesData[index]['cat_id'].toString();
  //         loadList();
  //       });
  //     },
  //   );
  // }

  Widget _renderRow(BuildContext context, int index) {
    var price = RichText(
      textAlign: TextAlign.left,
      text: TextSpan(style: TextStyle(color: Colors.red), children: [
        TextSpan(text: '¥', style: TextStyle(fontSize: 12.0)),
        TextSpan(
            text: homeListData[index].price, style: TextStyle(fontSize: 18.0)),
        TextSpan(
          text: homeListData[index].old_price,
          style: TextStyle(
              fontSize: 12.0,
              color: Colors.grey,
              decoration: TextDecoration.lineThrough,
              decorationColor: Colors.grey),
        ),
      ]),
      maxLines: 1,
      overflow: TextOverflow.ellipsis,
    );
    return new GestureDetector(
        onTap: () {
          //处理点击事件
          GoodsModelData model = homeListData[index];

          Navigator.of(context).push(new MaterialPageRoute(builder: (context) {
            return GoodsDetailPage(
              goods_id: model.goods_id,
              img: model.img,
            );
          }));
        },
        child: Column(
          children: <Widget>[
            Container(
              padding: EdgeInsets.all(10),
              color: white,
              child: new Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: <Widget>[
                  homeListData[index].img == ''
                      ? Image.asset('images/pic_default.png')
                      : Image.network(
                          Api.BaseUrl +
                              'public/upload/' +
                              homeListData[index].img.replaceAll('\\', '/'),
                          width: ScreenUtil.getInstance().setHeight(180),
                          height: ScreenUtil.getInstance().setHeight(180),
                        ),
                  Expanded(
                    flex: 1,
                    child: Container(
                      padding: EdgeInsets.fromLTRB(10, 5, 5, 5),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: <Widget>[
                          Text(
                            homeListData[index].goods_name,
                            maxLines: 2,
                            overflow: TextOverflow.ellipsis,
                            style: TextStyle(
                                fontSize: ScreenUtil.getInstance().setSp(30),
                                color: black,
                                fontWeight: FontWeight.bold),
                          ),
                          Row(
                            children: <Widget>[
                              Expanded(
                                flex: 1,
                                child: price,
                              ),
                              Container(
                                margin: EdgeInsets.all(kMargin5),
                                child: Text(
                                    '已售' + homeListData[index].sales_volume,
                                    style: TextStyle(
                                        fontSize: 12.0, color: Colors.grey)),
                              ),
                            ],
                          ),
                        ],
                      ),
                    ),
                  ),
                ],
              ),
            ),
            Container(
              width: ScreenUtil.getInstance().setWidth(750),
              height: kMargin5,
              color: divideColor,
            )
          ],
        ));
  }

  //商品单个cell
  getItemContainer(BuildContext context, int index) {
    var price = RichText(
      textAlign: TextAlign.left,
      text: TextSpan(style: TextStyle(color: Colors.red), children: [
        TextSpan(text: '¥', style: TextStyle(fontSize: 12.0)),
        TextSpan(
            // text: shopData[index].zk_final_price,
            text: homeListData[index].price,
            style: TextStyle(fontSize: 18.0)),
        TextSpan(
          // text: shopData[index].reserve_price,
          text: homeListData[index].old_price,
          style: TextStyle(
              fontSize: 12.0,
              color: Colors.grey,
              decoration: TextDecoration.lineThrough,
              decorationColor: Colors.grey),
        ),
      ]),
      maxLines: 1,
      overflow: TextOverflow.ellipsis,
    );
    return new GestureDetector(
        onTap: () {
          //处理点击事件
          GoodsModelData model = homeListData[index];
          Navigator.of(context).push(new MaterialPageRoute(builder: (context) {
            return GoodsDetailPage(
              goods_id: model.goods_id,
              img: model.img,
            );
          }));
        },
        child: Container(
            color: Colors.white,
            padding: EdgeInsets.all(ScreenUtil.getInstance().setHeight(10)),
            // margin: EdgeInsets.fromLTRB(kMargin10, 0, kMargin10, 0),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                homeListData[index].img == ''
                    ? Image.asset('images/pic_default.png')
                    : CachedNetworkImage(
                        width: (ScreenUtil.getInstance().setWidth(750) - kMargin20) / 2,
                        height: (ScreenUtil.getInstance().setWidth(750) - kMargin20) / 2,
                        fit: BoxFit.fill,
                        imageUrl: Api.BaseUrl +
                            'public/upload/' +
                            homeListData[index].img.replaceAll('\\', '/'),
                        placeholder: (context, url) => Image.asset(
                          'images/pic_default.png',
                          width: (ScreenUtil.getInstance().setWidth(750) - kMargin20) / 2,
                          height: (ScreenUtil.getInstance().setWidth(750) - kMargin20) / 2,
                        ),
                        errorWidget: (context, url, error) => Image.asset(
                          'images/pic_default.png',
                          width: (ScreenUtil.getInstance().setWidth(750) - kMargin20) / 2,
                          height: (ScreenUtil.getInstance().setWidth(750) - kMargin20) / 2,
                        ),
                      ),
                                          Container(
                          height: 2,
                        ),
                        Row(
                          children: <Widget>[
                            ClipOval(
                                child: Image.asset(
                              'images/logo.png',
                              width: ScreenUtil.getInstance().setWidth(38),
                              height: ScreenUtil.getInstance().setWidth(38),
                            )),
                            Container(
                              margin: EdgeInsets.only(left:ScreenUtil.getInstance().setWidth(5) ),
                              child: Text('日尚臻选',style: TextStyle(fontSize:ScreenUtil.getInstance().setSp(22),color: Colors.grey ),)
                            )
                          ],
                        ),
                        Container(
                          height: 2,
                        ),
                    Text(
                      homeListData[index].goods_name,
                      maxLines: 2,
                      style: TextStyle(
                          fontWeight: FontWeight.bold,
                          fontSize: ScreenUtil.getInstance().setSp(30)),
                    ),
                    Container(
                      height: 4,
                    ),
                Container(
                      margin: EdgeInsets.all(kMargin5),
                      child: RichText(
                        textAlign: TextAlign.left,
                        text: TextSpan(
                            style: TextStyle(color: Colors.red),
                            children: [
                              // TextSpan(text: '¥', style: TextStyle(fontSize: 12.0)),
                              TextSpan(
                                  // text: shopData[index].zk_final_price,
                                  text: MONEY + homeListData[index].price,
                                  style: TextStyle(
                                      fontSize:
                                          ScreenUtil.getInstance().setSp(30),
                                      fontWeight: FontWeight.w600)),
                              TextSpan(
                                // text: shopData[index].reserve_price,
                                text: homeListData[index].old_price,
                                style: TextStyle(
                                    fontSize: 12.0,
                                    color: Colors.grey,
                                    decoration: TextDecoration.lineThrough,
                                    decorationColor: Colors.grey),
                              ),
                            ]),
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                      ),
                    ),
              ],
            )));
  }


  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    cat_id = widget.cat_id;
    // subcate();
    loadList();
  }

  // subcate() async {
  //   Map map = new Map.from({
  //     "sign_type": createSignType(Api.URL_GOODSCAT_SUBLIST),
  //     "pid": cat_id,
  //   });
  //   Response<String> response =
  //       await HttpUtil().post(Api.URL_GOODSCAT_SUBLIST, data: getSign(map));
  //   Map userMap = json.decode(response.data);
  //   GoodsModelEntity itemEntity = new GoodsModelEntity.fromJson(userMap);
  //   print(userMap);
  //   if (itemEntity.code == 1) {
  //     setState(() {
  //       catesData.addAll(userMap['data']['list']);
  //     });
  //   } else {}
  // }

  loadList() async {
    Map map = new Map.from({
      "sign_type": createSignType(Api.URL_GOODS_LIST),
      "cat_id":widget.cat_id,
      'per': "10",
      'p': page.toString(),
      'orderby': sort
    });
    Response<String> response =
        await HttpUtil().post(Api.URL_GOODS_LIST, data: getSign(map));
    Map userMap = json.decode(response.data);
    GoodsModelEntity itemEntity = new GoodsModelEntity.fromJson(userMap);
    print(userMap);
    if (itemEntity.code == 1) {
      if (mounted) {
        setState(() {
          if (page == 1) {
            homeListData.clear();
            _controller.finishRefresh();
            homeListData = itemEntity.data;
          } else {
            _controller.finishLoad();
            homeListData.addAll(itemEntity.data);
          }
        });
      }
    }
  }
}
